﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.Utils;
using System.Threading;
using HostAssistantCore;
using HostAssistantBLL;
using DevExpress.XtraCharts;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace HostAssistant
{

    #region 信息结构 
    //定义CPU的信息结构    
    [StructLayout(LayoutKind.Sequential)]
    public struct CPU_INFO
    {
        public uint dwOemId;
        public uint dwPageSize;
        public uint lpMinimumApplicationAddress;
        public uint lpMaximumApplicationAddress;
        public uint dwActiveProcessorMask;
        public uint dwNumberOfProcessors;
        public uint dwProcessorType;
        public uint dwAllocationGranularity;
        public uint dwProcessorLevel;
        public uint dwProcessorRevision;
    }
    //定义内存的信息结构    
    [StructLayout(LayoutKind.Sequential)]
    public struct MEMORY_INFO
    {
        public uint dwLength;
        public uint dwMemoryLoad;
        public uint dwTotalPhys;
        public uint dwAvailPhys;
        public uint dwTotalPageFile;
        public uint dwAvailPageFile;
        public uint dwTotalVirtual;
        public uint dwAvailVirtual;
    }
    //定义系统时间的信息结构    
    [StructLayout(LayoutKind.Sequential)]
    public struct SYSTEMTIME_INFO
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMilliseconds;
    } 
    #endregion

    public partial class index : U1UserControl
    {
        #region 变量

        private const string CategoryName = "Processor";
        private const string CounterName = "% Processor Time";
        private const string InstanceName = "_Total";

        [DllImport("kernel32")]
        public static extern void GetSystemDirectory(StringBuilder SysDir, int count);
        [DllImport("kernel32")]
        public static extern void GetSystemInfo(ref CPU_INFO cpuinfo);
        [DllImport("kernel32")]
        public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo);
        [DllImport("kernel32")]
        public static extern void GetSystemTime(ref SYSTEMTIME_INFO stinfo);

        public static PerformanceCounter cpu;

        #endregion

        public index()
        {
            InitializeComponent();
      
        }

        #region 硬盘
        /// <summary>
        /// 硬盘
        /// </summary>
        void yp()
        {
            ChartControl sideBySideBarChart = new ChartControl();
            Series series1 = new Series("总量(G)", ViewType.Bar);
            Series series2 = new Series("使用(G)", ViewType.Bar);
            DriveInfo[] allDirves = DriveInfo.GetDrives();
            foreach (DriveInfo item in allDirves)
            {
                series1.Points.Add(new SeriesPoint(item.Name, (item.TotalSize / (1024 * 1024 * 1024))));
                series2.Points.Add(new SeriesPoint(item.Name, ((item.TotalSize / (1024 * 1024 * 1024)) - (item.TotalFreeSpace / (1024 * 1024 * 1024)))));
            }
            sideBySideBarChart.Series.Add(series1);
            sideBySideBarChart.Series.Add(series2);
            sideBySideBarChart.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;
            ChartTitle chartTitle1 = new ChartTitle();
            chartTitle1.Text = "硬盘空间情况";
            sideBySideBarChart.Titles.Add(chartTitle1);
            sideBySideBarChart.Dock = DockStyle.Fill;
            // groupControl2.Controls.Add(sideBySideBarChart);

            SetText3(sideBySideBarChart);
        }

        #endregion

        #region 委托
        private delegate void SetLabelDelegate(string value);

        private void SetText(string value)
        {
            if (this.InvokeRequired)
            {
                SetLabelDelegate d = new SetLabelDelegate(SetText);
                this.Invoke(d, new object[] { value });
            }
            else
            {
                if(value=="1")
                {
                    splashScreenManager1.ShowWaitForm();
                    splashScreenManager1.SetWaitFormCaption("请等待");
                    splashScreenManager1.SetWaitFormDescription("加载中...");

                } else if(value=="2")
                {
                    splashScreenManager1.CloseWaitForm();
                }
                else if (value == "3")
                {
                    LBLFTP.Text = ftpbll.GetsiteList(null).Count().ToString();
                    lblsite.Text = sitebll.GetsiteList(null, null).Count().ToString();
                    lblmysql.Text = dbbll.GetsiteList(null, null).Where(o => o.type == "mysql").Count().ToString();
                    lblmssql.Text = dbbll.GetsiteList(null, null).Where(o => o.type == "mssql").Count().ToString();


                }



            }
        }

        private delegate void SetLabelDelegate3(ChartControl value);

        private void SetText3(ChartControl value)
        {
            if (this.InvokeRequired)
            {
                SetLabelDelegate3 d = new SetLabelDelegate3(SetText3);
                this.Invoke(d, new object[] { value });
            }
            else
            {

              
               groupControl2.Controls.Add(value);

            }
        }


        #endregion

        #region fw

        void fw(object s)
        {
            try
            {
                SetText("1");


                yp();

                BuilderDevChart();

                BuildermenChart();

                SetText("2");
                SetText("3");

            }
            catch (Exception ex)
            {
                NLogger.Error(ex.ToString());
                SetText("2");
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }


        }

        #endregion

        #region _Load

        private void sitelist_Load(object sender, EventArgs e)
        {


            string s = "";
            ThreadPool.QueueUserWorkItem(new WaitCallback(fw), s);


        }

        #endregion

        #region 数据

        DataTable CreateChartData(string type)
        {
            DataTable table = new DataTable("Table1");
            table.Columns.Add("Name", typeof(String));
            table.Columns.Add("Value", typeof(Int32));



            cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            // cif = new ComputerInfo();  
            MEMORY_INFO MemInfo;
            MemInfo = new MEMORY_INFO();
            while (true)
            {

                if (type == "内存")
                {
                    GlobalMemoryStatus(ref MemInfo);
                    Console.WriteLine(MemInfo.dwMemoryLoad.ToString() + "%的内存正在使用");
                    //  MessageBox.Show(MemInfo.dwMemoryLoad.ToString());


                    if (ZConvert.StrToInt(MemInfo.dwMemoryLoad.ToString()) > 0)
                    {
                        table.Rows.Add(new object[] { "使用率", MemInfo.dwMemoryLoad.ToString() });
                        table.Rows.Add(new object[] { "空闲率", 100 - (ZConvert.StrToInt(MemInfo.dwMemoryLoad.ToString())) });
                        break;
                    }


                }
                else
                {






                    var percentage = cpu.NextValue();
                    Console.WriteLine(percentage + "%的CPU正在使用\n");


                    if (percentage > 0)
                    {
                        table.Rows.Add(new object[] { "使用率", percentage });
                        table.Rows.Add(new object[] { "空闲率", 100 - percentage });
                        break;
                    }
                }
                System.Threading.Thread.Sleep(20);
            }




            return table;
        }

        #endregion

        #region 饼状Series设置成百分比显示
        /////// <summary>
        /////// 饼状Series设置成百分比显示
        /////// </summary>
        /////// <param name="series">Series</param>
        void SetPiePercentage(Series series)
        {
            if (series.View is PieSeriesView)
            {
                ((PiePointOptions)series.PointOptions).PercentOptions.ValueAsPercent = true;
                ((PiePointOptions)series.PointOptions).ValueNumericOptions.Format = NumericFormat.Percent;
                ((PiePointOptions)series.PointOptions).ValueNumericOptions.Precision = 0;
            }
        }

        #endregion

        #region cpu
        /// <summary>
        /// cpu   
        /// </summary>
        void BuilderDevChart()
        {
            Series _pieSeries = new Series("测试", ViewType.Pie);
            _pieSeries.ValueDataMembers[0] = "Value";
            _pieSeries.ArgumentDataMember = "Name";
            _pieSeries.DataSource = CreateChartData("cpu");
            chartControl1.Series.Add(_pieSeries);
            //----------------------------------------
            _pieSeries.LegendPointOptions.PointView = PointView.ArgumentAndValues;
            SetPiePercentage(_pieSeries);
        }

        #endregion

        #region 内存

        /// <summary>
        /// 内存
        /// </summary>
        void BuildermenChart()
        {
            Series _pieSeries = new Series("测试", ViewType.Pie);
            _pieSeries.ValueDataMembers[0] = "Value";
            _pieSeries.ArgumentDataMember = "Name";
            _pieSeries.DataSource = CreateChartData("内存");
            chartControl2.Series.Add(_pieSeries);
            //----------------------------------------
            _pieSeries.LegendPointOptions.PointView = PointView.ArgumentAndValues;
            SetPiePercentage(_pieSeries);
        }

        #endregion
    }
}